package com.zhang.common.security.config;

import com.zhang.common.core.config.FilterIgnorePropertiesConfig;
import com.zhang.common.security.component.ZswUserAuthenticationConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * 资源服务器
 * ResourceServerConfig 用于保护oauth相关的endpoints，同时主要作用于用户的登录(form login,Basic auth)
 * 在ResourceServerConfigurerAdapter配置需要token验证的资源
 * <p>
 * <p>
 * 是默认情况下spring security oauth2的http配置
 */

@Slf4j
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    UnauthorizedEntryPoint unauthorizedEntryPoint;

    @Autowired
    protected RemoteTokenServices remoteTokenServices;

    @Autowired
    private FilterIgnorePropertiesConfig ignorePropertiesConfig;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private RestTemplate lbRestTemplate;


    @Override
    public void configure(HttpSecurity http) throws Exception {
        log.debug("放行的urls[{}]", Arrays.toString(ignorePropertiesConfig.getUrls().toArray()));
        //允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>
                .ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        ignorePropertiesConfig.getUrls()
                .forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated()
                .and().csrf().disable();

    }

    /**
     * Spring Security OAuth2 架构上分为Authorization Server和Resource Server。
     * 我们可以为每一个Resource Server（一个微服务实例）设置一个resourceid。再给client授权的时候，
     * 可以设置这个client可以访问哪一些微服务实例，如果没设置，就是对所有的resource都有访问权限。
     * @param resources
     * @throws Exception
     */
//    @Override
//    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
//        resources.resourceId("auth");
//    }



    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        log.info("调用方法--》PigResourceServerConfigurerAdapter.configure(ResourceServ");
        // 设置token解析器
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        UserAuthenticationConverter userTokenConverter = new ZswUserAuthenticationConverter();


        accessTokenConverter.setUserTokenConverter(userTokenConverter);
        //设置远程远程调用服务，以及配置

        remoteTokenServices.setRestTemplate(lbRestTemplate);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);

        resources.authenticationEntryPoint(unauthorizedEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)
                .tokenServices(remoteTokenServices);
    }
}